package Base64知识点;

import java.io.*;
import java.net.URL;
import java.util.Base64;

public class ImageUtils {

    /**
     * 在线图片 URL 转为 Base64 字符串
     * @param imageUrl 图片的在线地址
     * @return Base64 编码字符串
     * @throws IOException 网络异常或读取失败
     */
    public static String convertImageUrlToBase64(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        try (InputStream is = url.openStream();
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[8192]; // 缓冲区
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }

            // 获取字节数组并进行 Base64 编码
            byte[] imageBytes = baos.toByteArray();
            return Base64.getEncoder().encodeToString(imageBytes);
        }
    }

    // 示例入口
    public static void main(String[] args) throws IOException {
        String url = "http://link.jpg";
        String base64 = convertImageUrlToBase64(url);
        System.out.println("Base64 编码结果：" + base64);
    }
}
